package com.topone.service;


import com.topone.Exception.FanZoneServiceException;
import com.topone.dataObject.Image;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.InputStream;

@Service
@Slf4j
public class FileLocalStorageService {

    @Autowired
    private ImageService imageService;


    public Image loadImage(Integer imageId) {
        return loadLocalImage(imageId, false);
    }

    private Image loadLocalImage(Integer imageId, boolean isThumbnails) {
        try {
            Image image = imageService.findImageById(imageId);
            if (image == null) {
                throw new FanZoneServiceException(String.format("未发现文件[%d]", imageId));
            }
            if (isThumbnails && StringUtils.isEmpty(image.getImgPath())) {
                try (InputStream in = new FileInputStream(image.getImgPath())) {
                    byte[] data = IOUtils.toByteArray(in);
                    image.setDataInput(new ByteArrayInputStream(data));
                    return image;
                }
            }
            if (StringUtils.isNotEmpty(image.getImgPath())) {
                image.setDataInput(new FileInputStream(image.getImgPath()));
            } else {
                image.setDataInput(new ByteArrayInputStream("".getBytes()));
            }
            return image;
        } catch (Exception ex) {
            log.error("Error: {}", ex.fillInStackTrace());
            throw new FanZoneServiceException(String.format("未发现文件[%d]", imageId));
        }
    }

}
